package xjtu.se.articlecommunity.common.base;


import xjtu.se.articlecommunity.common.*;
import xjtu.se.articlecommunity.common.dto.CurrentUser;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/admin/*")
public class AdminFilter implements Filter {

    @Resource
    private CommonService commonService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        String[] paths = request.getServletPath().split("/");


        if("login".equals(paths[2])){

            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String clientToken = request.getHeader("AToken");

        try {
            TokenUtils.verifyToken(clientToken,commonService);
            filterChain.doFilter(servletRequest,servletResponse);

        } catch (RuntimeException e) {
            e.printStackTrace();
            Utils.outJson(response, Result.fail(Result.ERR_CODE_AUNLOGIN,e.getMessage()));

        }
    }

    @Override
    public void destroy() {

    }
}
